package com.cart.service;

import com.cart.dao.CartDao;
import com.cart.entity.Cart;
import com.cart.entity.CartFinal;
import com.cart.entity.Product;
import com.cart.util.CommonResponse;
import com.cart.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {
    @Autowired
    CartDao cartDao;
    @Autowired
    TokenUtil tokenUtil;
    //查看购物车
    public CommonResponse showCart(String token){
        List<CartFinal> cartFinals = cartDao.selectCart(tokenUtil.getUserId(token));

        if (!cartFinals.isEmpty()){
            Float totalFloat = 0f;
            for(CartFinal cartFinal:cartFinals){
                totalFloat += Float.parseFloat(cartFinal.getPrice())*cartFinal.getNum();
            }
            String totalString = String.valueOf(totalFloat);
            String total = totalString.substring(0,totalString.indexOf(".")+3);
            return new CommonResponse(200,total,cartFinals);
        }
        else
            return new CommonResponse(500,"empty");
    }
    //向购物车中添加商品
    public CommonResponse addToCart(String token, int fnum,String fname){
        int id = tokenUtil.getUserId(token);
        //当前库存
        List<Integer> list = cartDao.selectSum(fname);
        int nowSum = list.get(0);
        if(fnum<=nowSum) {
            cartDao.updateSum(nowSum-fnum,fname);
            cartDao.addToCart(id,fname,fnum);
            return new CommonResponse(200, "update ok!");
        }
        else
            return new CommonResponse(500,"num not enough!");
    }

}
